//
//  UserInfoViewController.m
//  demoapp
//
//  Created by MingmingSun on 15/9/22.
//  Copyright (c) 2015年 pingplusplus. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UIImageView+AFNetworking.h"
#import "UIButton+AFNetworking.h"
#import "tooles.h"

@interface UserInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UITextViewDelegate,UITextFieldDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong) NSDictionary *customerDic;

@property(nonatomic,weak) IBOutlet UITableView *listView;

@property(nonatomic,weak) UIButton *headButton;

@property(nonatomic,strong) NSData *headImageData;

@property(nonatomic,weak) UIButton *xzButton;
@property(nonatomic,weak) UIButton *fxButton;
@property(nonatomic,weak) UIButton *fzButton;
@property(nonatomic,weak) UIButton *fsButton;
//昵称 简介 年龄 籍贯 职业 爱好
@property(nonatomic,weak) UITextField *ncField;
@property(nonatomic,weak) UITextField *jjField;
@property(nonatomic,weak) UITextField *nlField;
@property(nonatomic,weak) UITextField *jgField;
@property(nonatomic,weak) UITextField *zyField;
@property(nonatomic,weak) UITextField *ahField;
@property(nonatomic,weak) UISegmentedControl *xbSeg;

typedef enum
{
    SheetTagPhoto = 1,
    SheetTagXZ,
    SheetTagFX,
    SheetTagFZ,
    SheetTagFS,
}SheetTag;
@property(nonatomic,assign) SheetTag mySheetTag;



@property(nonatomic,assign) int buttonIndex;

-(IBAction)buttonPressed:(id)sender;

@property(nonatomic,assign) BOOL isModify;

@end

@implementation UserInfoViewController

@synthesize listView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"我的资料";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithTitle:@"修改"
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(modifyPressed:)];
        self.customerDic = nil;
        self.isModify = NO;
        self.headImageData = nil;
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)modifyPressed:(id)sender{
    self.isModify = !self.isModify;
    self.navigationItem.rightBarButtonItem.title = self.isModify?@"保存":@"修改";
    if(!self.isModify){
        [self nextPressed:nil];
    }else{
        [self.listView reloadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.buttonIndex = 1;
    [self fetchCouponLists];
}

-(IBAction)buttonPressed:(id)sender{
    self.buttonIndex = [sender tag];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)fetchCouponLists {
    NSDictionary *para = @{@"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"customer_see"
                       withParameters:para
                                block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    self.customerDic = (NSDictionary*)[aSucData objectForKey:@"customer"];
                    [listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.customerDic?5:0;//self.barberArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            return 355.0f;
        case 1:
        case 2:
        case 3:
        case 4:
            return 46.0f;
        default:
            return 0.0f;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    switch (indexPath.row) {
        case 0:{
            inde = @"UserInputTitleID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserInputTitle" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            if(!self.headButton)
            {
                self.headButton = (UIButton*)[cell viewWithTag:1];
                self.headButton.layer.masksToBounds =YES;
                self.headButton.layer.cornerRadius = self.headButton.frame.size.width/2;
                [self.headButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@user/head?token=%@",APPALL.globalUrl,APPALL.myUserItem.token]]
                   placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
                [self.headButton addTarget:self
                                        action:@selector(headPressed:)
                              forControlEvents:UIControlEventTouchUpInside];
            }
            UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
            lab2.text = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"authUser"]];
            UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
            lab3.text = [NSString stringWithFormat:@"积分:%i",[[self.customerDic valueForKey:@"points"] integerValue]];
            if(!self.ncField){
                self.ncField = (UITextField*)[cell viewWithTag:4];
                self.ncField.text = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"name"]];
            }
            self.ncField.enabled = self.isModify;
            if(!self.jjField){
                self.jjField = (UITextField*)[cell viewWithTag:5];
                self.jjField.text = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"intro"]];
            }
            self.jjField.enabled = self.isModify;
            if(!self.nlField){
                self.nlField = (UITextField*)[cell viewWithTag:6];
                self.nlField.text = [NSString stringWithFormat:@"%@",[tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"age"]]];
            }
            self.nlField.enabled = self.isModify;
            if(!self.jgField){
                self.jgField = (UITextField*)[cell viewWithTag:7];
                self.jgField.text = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"origin"]];
            }
            self.jgField.enabled = self.isModify;
            if(!self.zyField){
                self.zyField = (UITextField*)[cell viewWithTag:8];
                self.zyField.text = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"occupation"]];
            }
            self.zyField.enabled = self.isModify;
            if(!self.ahField){
                self.ahField = (UITextField*)[cell viewWithTag:9];
                self.ahField.text = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"beFondOf"]];
            }
            self.ahField.enabled = self.isModify;
            if(!self.xbSeg){
                self.xbSeg = (UISegmentedControl*)[cell viewWithTag:11];
                [self.xbSeg addTarget:self action:@selector(genderChanged:) forControlEvents:UIControlEventValueChanged];
                NSString *str = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"gender"]];
                NSRange foundObj;
                foundObj=[str rangeOfString:@"男" options:NSCaseInsensitiveSearch];
                if(foundObj.length>0) {
                    self.xbSeg.selectedSegmentIndex = 0;
                } else {
                    self.xbSeg.selectedSegmentIndex = 1;
                }
            }
            self.xbSeg.enabled = self.isModify;
        }
            break;
        case 1:{
            inde= @"userbuttonsid";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserInputButton" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            lab1.text = @"星座:";
            if(!self.xzButton)
            {
                NSString *xzStr = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"constellation"]];
                self.xzButton = (UIButton*)[cell viewWithTag:2];
                [self.xzButton setTitle:xzStr.length?xzStr:@"选择星座" forState:UIControlStateNormal];
                [self.xzButton addTarget:self
                                  action:@selector(xzPressed:)
                        forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;
        case 2:{
            inde= @"userbuttonsid";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserInputButton" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            lab1.text = @"发型:";
            if(!self.fxButton)
            {
                NSString *fxStr = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"hairType"]];
                self.fxButton = (UIButton*)[cell viewWithTag:2];
                [self.fxButton setTitle:fxStr.length?fxStr:@"选择发型" forState:UIControlStateNormal];
                [self.fxButton addTarget:self
                                  action:@selector(fxPressed:)
                        forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;
        case 3:{
            inde= @"userbuttonsid";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserInputButton" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            lab1.text = @"发质:";
            if(!self.fzButton)
            {
                NSString *fxStr = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"hairNature"]];
                self.fzButton = (UIButton*)[cell viewWithTag:2];
                [self.fzButton setTitle:fxStr.length?fxStr:@"选择发质" forState:UIControlStateNormal];
                [self.fzButton addTarget:self
                                  action:@selector(fzPressed:)
                        forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;
        case 4:{
            inde= @"userbuttonsid";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"UserInputButton" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            lab1.text = @"发色:";
            if(!self.fsButton)
            {
                NSString *fxStr = [tooles replaceNullFromDic:self.customerDic withKeyArray:@[@"hairColor"]];
                self.fsButton = (UIButton*)[cell viewWithTag:2];
                [self.fsButton setTitle:fxStr.length?fxStr:@"选择发色" forState:UIControlStateNormal];
                [self.fsButton addTarget:self
                                  action:@selector(fsPressed:)
                        forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;
        default:
            break;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //nothing
}

-(void)headPressed:(id)sender{
    return;
    [self resignAllTextField];
    self.mySheetTag = SheetTagPhoto;
    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"立即拍照",@"从本地选", nil];
    [chooseImageSheet showInView:self.view];
}

-(void)xzPressed:(id)sender{
    if(!self.isModify)
        return;
    self.mySheetTag = SheetTagXZ;
    UIActionSheet *actionSheet;
    actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择星座"
                                              delegate:self
                                     cancelButtonTitle:@"取消"
                                destructiveButtonTitle:nil
                                     otherButtonTitles:@"白羊",@"金牛",@"双子",@"巨蟹",@"狮子",@"处女",@"天秤",@"天蝎",@"射手",@"摩羯",@"水瓶",@"双鱼",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

-(void)fxPressed:(id)sender{
    if(!self.isModify)
        return;
    self.mySheetTag = SheetTagFX;
    UIActionSheet *actionSheet;
    if([self.xbSeg selectedSegmentIndex]){
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择发型"
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:@"长发",@"中发",@"短发",@"直发",@"卷发",@"编发",@"潮流",@"明星",@"宴会",@"新娘",nil];
    }else{
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择发型"
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:@"长发",@"中发",@"短发",@"直发",@"卷发",@"编发",@"潮流",@"明星",@"宴会",nil];
    }
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

-(void)fzPressed:(id)sender{
    if(!self.isModify)
        return;
    self.mySheetTag = SheetTagFZ;
    UIActionSheet *actionSheet;
    actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择发质"
                                              delegate:self
                                     cancelButtonTitle:@"取消"
                                destructiveButtonTitle:nil
                                     otherButtonTitles:@"正常发质",@"受损发质",@"粗硬发质",@"细软发质",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

-(void)fsPressed:(id)sender{
    if(!self.isModify)
        return;
    self.mySheetTag = SheetTagFS;
    UIActionSheet *actionSheet;
    actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择发色"
                                              delegate:self
                                     cancelButtonTitle:@"取消"
                                destructiveButtonTitle:nil
                                     otherButtonTitles:@"黑色",@"白色",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self resignAllTextField];
}

-(void)resignAllTextField
{
    if(self.ncField.isFirstResponder)
        [self.ncField resignFirstResponder];
    if(self.jjField.isFirstResponder)
        [self.jjField resignFirstResponder];
    if(self.nlField.isFirstResponder)
        [self.nlField resignFirstResponder];
    if(self.jgField.isFirstResponder)
        [self.jgField resignFirstResponder];
    if(self.zyField.isFirstResponder)
        [self.zyField resignFirstResponder];
    if(self.ahField.isFirstResponder)
        [self.ahField resignFirstResponder];
}

-(void)genderChanged:(id)sender
{
    if(![self.xbSeg selectedSegmentIndex]){
        if([[self.fxButton titleForState:UIControlStateNormal] isEqualToString:@"新娘"]){
            [self.fxButton setTitle:@"长发" forState:UIControlStateNormal];
        }
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"...%d",buttonIndex);
    //    if(buttonIndex)
}

-(void)ImageSelectTrue:(id)sender
{
    [self resignAllTextField];
}

#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (self.mySheetTag) {
        case SheetTagPhoto:
        {
            switch (buttonIndex) {
                case 0://Take picture
                {
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        [self takePhoto:NO];
                    }
                    else
                    {
                        NSLog(@"模拟器无法拍照");
                        [self takePhoto:YES];
                    }
                }
                    break;
                case 1://From album
                {
                    [self takePhoto:YES];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case SheetTagXZ:{
            if(buttonIndex >= actionSheet.numberOfButtons - 1)
                break;
            [self.xzButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
        }
            break;
        case SheetTagFZ:{
            if(buttonIndex >= actionSheet.numberOfButtons - 1)
                break;
            [self.fzButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
        }
            break;
        case SheetTagFX:{
            if(buttonIndex >= actionSheet.numberOfButtons - 1)
                break;
            [self.fxButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
        }
            break;
        case SheetTagFS:{
            if(buttonIndex >= actionSheet.numberOfButtons - 1)
                break;
            [self.fsButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
        }
            break;
        default:
            break;
    }
}

-(void)takePhoto:(BOOL)localornot
{
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = localornot?UIImagePickerControllerSourceTypePhotoLibrary:UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:NO completion:^{
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        NSLog(@"mediaType:%@",mediaType);
        if ([mediaType isEqualToString:@"public.image"]){
            UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            if(originImage==nil) return;
            UIImage *rotatedImage = [tooles rotateImage:originImage];
            UIImage *scaleImage = [tooles scaleImage:rotatedImage];
            [self.headButton setImage:scaleImage forState:UIControlStateNormal];
            self.headImageData = UIImageJPEGRepresentation(scaleImage,0.4f);
#if 0
            if(!self.mainPicImageData.length)
            {
                [SVProgressHUD showErrorWithStatus:@"没有上传主照片！"];
                return;
            }
            //你的接口地址
            ///////////////////////////////////////////////////////////////
            NSString *url=[NSString stringWithFormat:@"%@show/create",APPALL.globalUrl];
            //发送请求
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"JSON: %@",responseObject);
                int succInt = [[(NSDictionary*)responseObject valueForKey:@"success"] intValue];
                if(succInt){
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[(NSDictionary*)responseObject valueForKey:@"code"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                [SVProgressHUD dismiss];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"Error: %@", error);
                [tooles showGlobalAlertWithTitle:@"" andMsg:[NSString stringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            }];
#endif
        }
    }];
}

-(void)nextPressed:(id)sender
{
    [self resignAllTextField];
    NSDictionary *para =
    @{@"id":[self.customerDic valueForKey:@"id"],
      @"name":self.ncField.text,
      @"gender":self.xbSeg.selectedSegmentIndex?@"女":@"男",
      @"intro":self.jjField.text,
      @"origin":self.jgField.text,
      @"age":self.nlField.text,
      @"occupation":self.zyField.text,
      @"beFondOf":self.ahField.text,
      @"constellation":[self.xzButton titleForState:UIControlStateNormal],
      @"hairNature":[self.fzButton titleForState:UIControlStateNormal],
      @"hairType":[self.fxButton titleForState:UIControlStateNormal],
      @"hairColor":[self.fsButton titleForState:UIControlStateNormal],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"customer" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    [self.listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}


-(void)dealloc
{
    self.headImageData = nil;
}

@end